import './public-path.js'
import Vue from 'vue'
import App from './App.vue'
import routes from './router'
import store from './store'
import VueRouter from 'vue-router'

Vue.config.productionTip = false

let instance = null
let router = null;

function render() {
  router = new VueRouter({
    mode: 'history',
    base: process.env.VUE_APP_MODULE,
    routes
  })
  router.beforeEach((to, from, next) => {
    console.log({to, from})
    next()
  })

  if (
    window.__POWERED_BY_QIANKUN__ &&
    window.__CACHE_INSTANCE_BY_QIAN_KUN_FOR_VUE__
  ) {
    const cachedInstance = window.__CACHE_INSTANCE_BY_QIAN_KUN_FOR_VUE__;

    console.log('>>> cachedInstance', cachedInstance)
    // 从最初的Vue实例上获得_vnode
    const cachedNode = cachedInstance._vnode;

    // 让当前路由在最初的Vue实例上可用
    router.apps.push(...cachedInstance.$router.apps);
    // keepAlive可用
    cachedNode.data.keepAlive = true;

    instance = new Vue({
      router,
      store,
      render: () => cachedNode
    });

    // 缓存最初的Vue实例
    instance.cachedInstance = cachedInstance;

    router.onReady(() => {
      const { fullPath } = instance._route;
      const { fullPath: oldPath } = cachedInstance._route;
      console.log('>>> router path', {
        fullPath,
        oldPath
      })

      if (fullPath !== oldPath) {
        router.replace(oldPath);
      }
    });

    instance.$mount("#app");
  } else {
    // 正常实例化
    instance = new Vue({
      router,
      store,
      render: h => h(App)
    }).$mount('#app')
  }
}

if (!window.__POWERED_BY_QIANKUN__) {
  render()
}

export async function bootstrap() {
  console.log('app2 bootstrapped')
}

export async function mount(props) {
  console.log('app2 mount', props)
  render()
}

export async function unmount() {
  console.log('[vue] vue app unmount', instance);
  const cachedInstance = instance.cachedInstance || instance;
  window.__CACHE_INSTANCE_BY_QIAN_KUN_FOR_VUE__ = cachedInstance;
  const cachedNode = cachedInstance._vnode;
  cachedNode.data.keepAlive = true;
  cachedNode.data.hook.destroy(cachedNode);
  if (instance.cachedInstance) {
    instance.$destroy();
    instance = null;
  }
  router = null;
}
